/* eslint-disable no-undef */
/* eslint-disable eqeqeq */
const httpProxy = require('http-proxy');
const https = require('https');
const http = require('http');
const fs = require('fs');
const path = require('path');

const proxyTable = {
  '/api': 'http://localhost:9000',
  '/': 'http://localhost:8000',
};

// 创建代理服务器实例
const proxy = httpProxy.createProxyServer({});

// 错误处理
proxy.on('error', (err, req, res) => {
  res.writeHead(500, { 'Content-Type': 'text/plain' });
  res.end('Something went wrong. And we are reporting a custom error message.');
});

// 创建HTTPS服务器
const sslOptions = {
  key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
  cert: fs.readFileSync(path.resolve(__dirname, 'server.crt')),
};

// HTTPS监听
https
  .createServer(sslOptions, function (req, res) {
    if (req.url.indexOf('/api') == 0) target = proxyTable['/api'];
    else target = proxyTable['/'];

    if (target) {
      // 如果请求路径存在于代理表中，则进行代理转发
      proxy.web(req, res, { target });
    } else {
      // 如果没有匹配的代理路径，则发送 404 Not Found
      res.writeHead(404);
      res.end();
    }
  })
  .listen(9002, () => {
    console.log('HTTPS Proxy Server is listening on port 9000');
  });
